<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2019/3/18 0018
 * Describe: 贷款执行的定时任务类
 */

namespace app\admin\controller\timingtask;

use think\Controller;
use app\admin\controller\Order;
use app\admin\controller\system\SmsTemplate;
use app\admin\controller\System;
use app\common\controller\chuanglan\ChuanglanSmsApi as CLApi;
use app\common\controller\system\Docking;
use think\Request;
use think\Log;

class Loan extends Controller
{
    public function __construct()
    {
        $requestName = Request::instance()->module();
        $controllerName = Request::instance()->controller();
        $setPath = strtolower("{$requestName}/{$controllerName}/");
        Log::init(['path'=>LOG_PATH.$setPath,'type'  => 'file',]);
    }

    /**
     * 贷款逾期的每天短信通知 【定时任务】
     */
    public function loanOverdueEveryDay()
    {
        //获取处于贷款逾期的用户数据
        $userData = $this->getOverdueUser();
        if(!$userData){
            \Think\Log::record('贷款逾期的每天短信通知 - 没有需要通知的用户');die;
        }

        //获取逾期短信内容模板
        $smsTemp = ((new SmsTemplate())->getSmsInfo('daily_inform'));
        $template = str_replace(['#name#','#days#','#money#'],['{$var}','{$var}','{$var}'],$smsTemp['Content']);

        $param = '';
        foreach ($userData as $k=>$v){
            //获取订单逾期天数
            $days = (new Order())->isOrderOverdue($v);

            //获取订单应还款金额
            $money = (new Order())->getOrderShould($v);

            //拼接短信请求参数
            $param = $v['Mobile'].','.$v['TrueName'].','.$days.','.$money.';'.$param;
        }

        $params = substr($param,0,-1);
        $result1 = (new CLApi())->sendVariableSMS($template,$params);
        $result2 = json_decode($result1,true);

        //写入对接产品记录表
        for($i=0;$i<count($userData);$i++){
            (new Docking())->addDocking(1,($result2['code'] == 0)?2:3,'chuanglan','贷款逾期的每天短信通知【定时任务】',$result1);
        }

        if($result2['code'] == 0){
            \Think\Log::record('贷款逾期的每天短信通知 - 通知成功 创蓝短信返回结果数据 - '.$result1);die;
        }else{
            \Think\Log::record('贷款逾期的每天短信通知 - 通知失败 创蓝短信返回结果数据 - '.$result1);die;
        }
    }

    /**
     * 借款到期当天通知 【定时任务】
     */
    public function loanExpireDayNotice()
    {
        //获取当日处于贷款到期的用户数据
        $userData = $this->getExpireUser();
        if(!$userData){
            \Think\Log::record('贷款逾期的每天短信通知 - 没有需要通知的用户');die;
        }

        //获取逾期短信内容模板
        $smsTemp = ((new SmsTemplate())->getSmsInfo('expire_lnform'));
        $template = str_replace(['#name#','#loan_time#','#money#'],['{$var}','{$var}','{$var}'],$smsTemp['Content']);

        $param = '';
        foreach ($userData as $k=>$v){
            //拼接短信请求参数
            $param = $v['Mobile'].','.$v['TrueName'].','.$v['ApplyTime'].','.$v['ApplyMoney'].';'.$param;
        }
        $params = substr($param,0,-1);
        $result1 = (new CLApi('hk'))->sendVariableSMS($template,$params);
        $result2 = json_decode($result1,true);

        //写入对接产品记录表
        for($i=0;$i<count($userData);$i++){
            (new Docking())->addDocking(1,($result2['code'] == 0)?2:3,'chuanglan','借款到期当天通知【定时任务】',$result1);
        }

        if($result2['code'] == 0){
            \Think\Log::record('借款到期当天通知 - 通知成功 创蓝短信返回结果数据 - '.$result1);die;
        }else{
            \Think\Log::record('借款到期当天通知 - 通知失败 创蓝短信返回结果数据 - '.$result1);die;
        }
    }

    /**
     * 借款提前一天通知 【定时任务】
     */
    public function loanAdvanceNotice()
    {
        //获取贷款即将到期的用户数据
        $userData = $this->getExpireAdvanceUser();
        if(!$userData){
            \Think\Log::record('借款提前一天通知 - 没有需要通知的用户');die;
        }

        //获取借款提前一天通知的短信内容模板
        $smsTemp = ((new SmsTemplate())->getSmsInfo('advance_inform'));
        $template = str_replace(['#name#','#loan_time#','#money#'],['{$var}','{$var}','{$var}'],$smsTemp['Content']);

        $param = '';
        foreach ($userData as $k=>$v){
            //拼接短信请求参数
            $param = $v['Mobile'].','.$v['TrueName'].','.$v['ApplyTime'].','.$v['ApplyMoney'].';'.$param;
        }
        $params = substr($param,0,-1);
        $result1 = (new CLApi('hk'))->sendVariableSMS($template,$params);
        $result2 = json_decode($result1,true);

        //写入对接产品记录表
        for($i=0;$i<count($userData);$i++){
            (new Docking())->addDocking(1,($result2['code'] == 0)?2:3,'chuanglan','借款提前一天通知【定时任务】',$result1);
        }

        if($result2['code'] == 0){
            \Think\Log::record('借款提前一天通知 - 通知成功 创蓝短信返回结果数据 - '.$result1);die;
        }else{
            \Think\Log::record('借款提前一天通知 - 通知失败 创蓝短信返回结果数据 - '.$result1);die;
        }
    }

    /**
     * 获取处于贷款逾期的用户信息
     * @return array
     */
    private function getOverdueUser(){

        $where['LoanStatus'] = 2;
        $where['YyFkTime'] = ['LT',date('Y-m-d',time())];
        return db('loans_applylist')->alias('a')
            ->join('xb_mem_info m','a.UserID = m.ID')
            ->where($where)
            ->field(['a.*','m.Mobile','m.TrueName'])
            ->select();
    }

    /**
     * 获取当日处于贷款到期的用户数据
     * @return array
     */
    private function getExpireUser(){

        $where['LoanStatus'] = 2;
        return db('loans_applylist')->alias('a')
            ->join('xb_mem_info m','a.UserID = m.ID')
            ->where($where)
            ->whereTime('YyFkTime', 'today')
            ->field(['a.*','m.Mobile','m.TrueName'])
            ->select();
    }

    /**
     * 获取贷款即将到期的用户数据
     */
    private function getExpireAdvanceUser(){

        //取明天时间范围
        $tomorrow = date("Y-m-d",strtotime("+1 day"));
        $where['LoanStatus'] = 2;
        return db('loans_applylist')->alias('a')
            ->join('xb_mem_info m','a.UserID = m.ID')
            ->where($where)
            ->whereTime('YyFkTime',[$tomorrow, $tomorrow.' 23:59:59'])
            ->field(['a.*','m.Mobile','m.TrueName'])
            ->select();
    }

}